package com.hzhh123.download;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.hzhh123.download.adapter.FileDownloadCompleteAdapter;
import com.hzhh123.download.model.File;
import com.hzhh123.download.utils.db.DbHelper;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnBindViewListener;
import com.timmy.tdialog.listener.OnViewClickListener;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.List;

public class DownloadCompleteActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private FrameLayout frameLayout1;
    private int mType=1;
    private Menu menu;
    //单击多选状态 0-反选 1-全选
    private int mCheckMoreStatus=0;
    private List<File>downloadCompleteFiles=new ArrayList<>();
    private List<File> selectFileList=new ArrayList<>();
    private FileDownloadCompleteAdapter adapter;
    private RecyclerView downloadRecycle;
    private LinearLayout delLinear,detailLinear;
    private Context mContext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_complete);
        mContext=this;
        initUI();
        getData();
        downloadRecycle=(RecyclerView)findViewById(R.id.download_recycle);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        downloadRecycle.setLayoutManager(linearLayoutManager);
        adapter=new FileDownloadCompleteAdapter(downloadCompleteFiles,this);
        downloadRecycle.setAdapter(adapter);
        initToolBar();
        itemEvent();


    }

    private void initUI(){
        frameLayout1=(FrameLayout) findViewById(R.id.fragment_1);
        delLinear=(LinearLayout)findViewById(R.id.del);
        detailLinear=(LinearLayout)findViewById(R.id.detail);
        delLinear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteFiles();
            }
        });
        detailLinear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                detailFiles();
            }
        });
    }

    private void deleteFiles(){
        if(selectFileList.size()==0){
            Toast.makeText(this, "请选择文件", Toast.LENGTH_SHORT).show();
        }else{
            AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle("删除")
                    .setMessage("确定要删除这"+selectFileList.size()+"个文件吗?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            removeFile(selectFileList);
                            downloadCompleteFiles.removeAll(selectFileList);
                            adapter.notifyDataSetChanged();
                            dialogInterface.dismiss();
                            toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.icon_back_white));
                            toolbar.setTitle("下载管理");
                            menu.getItem(0).setVisible(false);
                            frameLayout1.setVisibility(View.GONE);
                            for (File file:downloadCompleteFiles){
                                file.setShow(false);
                                file.setChecked(false);
                            }
                            selectFileList.clear();
                            mType=1;
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    });
            builder.create().show();
        }
    }

    /**
     * 查看文件详情
     */
    private void detailFiles(){
        if(selectFileList.size()!=1){
            Toast.makeText(this, "只能查看一个文件项", Toast.LENGTH_SHORT).show();
        }else{
            final File file=selectFileList.get(0);
            new TDialog.Builder(getSupportFragmentManager())
                    .setLayoutRes(R.layout.dialog_file_info)
                    .setScreenWidthAspect(mContext, 0.8f)
                    .addOnClickListener(R.id.tv_cancel)
                    .setDialogAnimationRes(R.style.animate_dialog_scale)
                    .setOnBindViewListener(new OnBindViewListener() {   //通过BindViewHolder拿到控件对象,进行修改
                        @Override
                        public void bindView(BindViewHolder bindViewHolder) {
                            bindViewHolder.setText(R.id.path,file.getPath());
                            bindViewHolder.setText(R.id.file_name,file.getFileName());
                            bindViewHolder.setText(R.id.size,file.getSizeStr());
                            bindViewHolder.setText(R.id.file_type,"application/"+file.getFileType());
                            bindViewHolder.setText(R.id.create_time,DateFormat.format("yyyy/MM/dd HH:mm:ss",file.getCreateTime()));
                        }
                    })
                    .setOnViewClickListener(new OnViewClickListener() {
                        @Override
                        public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                            switch (view.getId()) {
                                case R.id.tv_cancel:
                                    tDialog.dismiss();
                                    break;
                            }
                        }
                    })
                    .create()
                    .show();
        }
    }
    private void itemEvent(){
        adapter.setOnItemClickListener(new FileDownloadCompleteAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if(mType==2){
                    File file = downloadCompleteFiles.get(position);
                    if(file.isChecked()) {
                        file.setChecked(false);
                        selectFileList.remove(file);
                    }else{
                        file.setChecked(true);
                        selectFileList.add(file);
                    }
                    adapter.notifyDataSetChanged();
                    if(selectFileList.size()==0){
                        toolbar.setTitle("未选择");
                    }else {
                        toolbar.setTitle("已选择" + selectFileList.size() + "项");
                    }
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {
                frameLayout1.setVisibility(View.VISIBLE);
                toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.close_white));
                if(selectFileList.size()==0) {
                    toolbar.setTitle("未选择");
                }
                for (File file:downloadCompleteFiles){
                    file.setShow(true);
                }
                menu.getItem(0).setVisible(true);
                adapter.notifyDataSetChanged();
                mType=2;
            }
        });
    }
    /**
     * 初始化toolbar
     */
    private void initToolBar() {
        toolbar = findViewById(R.id.toolbar);
        //设置标题和颜色
        toolbar.setTitle("下载管理");
        toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        //动态添加菜单
        menu = toolbar.getMenu();
        menu.add("全选").setIcon(R.drawable.check_more2).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        menu.getItem(0).setVisible(false);
        menu.getItem(0).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if(mCheckMoreStatus==0){
                    for(File file:downloadCompleteFiles){
                        file.setChecked(true);
                    }
                    selectFileList.clear();
                    selectFileList.addAll(downloadCompleteFiles);
                    toolbar.setTitle("已选择"+selectFileList.size()+"项");
                    adapter.notifyDataSetChanged();
                    mCheckMoreStatus=1;
                }else{
                    for(File file:downloadCompleteFiles){
                        file.setChecked(false);
                    }
                    toolbar.setTitle("未选择");
                    selectFileList.clear();
                    adapter.notifyDataSetChanged();
                    mCheckMoreStatus=0;
                }
                return false;
            }
        });
        //返回菜单
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mType==1){
                    finish();
                }else{
                    toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.icon_back_white));
                    toolbar.setTitle("下载管理");
                    menu.getItem(0).setVisible(false);
                    frameLayout1.setVisibility(View.GONE);
                    for (File file:downloadCompleteFiles){
                        file.setShow(false);
                        file.setChecked(false);
                    }
                    selectFileList.clear();
                    adapter.notifyDataSetChanged();
                    mType=1;
                }
            }
        });
    }


    private void getData(){
        List<com.hzhh123.download.model.File>fileList=new ArrayList<>();
        DbManager db = DbHelper.getDbManager();
        try {
            fileList=db.selector(com.hzhh123.download.model.File.class).where("status","=",File.DOWNLOAD_COMPLETE).findAll();
            if(fileList!=null){
                downloadCompleteFiles=fileList;
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件
     * @param fileList
     */
    private void removeFile(List<File> fileList){
        DbManager db = DbHelper.getDbManager();
        try {
            for(File file:fileList) {
                db.delete(file);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }
}
